package com.lr.transfer.controller;

import com.lr.transfer.config.TransferProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Auther liran
 * @Date 2018/9/28 15:35
 * @Description
 */
@RestController
@Slf4j
public class DownLoadController extends BaseController {

    @Autowired
    private TransferProperties transferProperties;

    /**
     * 查询所用用户
     *
     * @return
     */
    @GetMapping("/lr/downLoad")
    public void downLoad(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setContentType("text/html;charset=utf-8");
        // request通过getParameter得到filename这个参数的值
        String filename = request.getParameter("filename");
        log.info("filename:{}", filename);
        // response设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        String path = null;
        // jpg和mp3都存在于web应用目录下，mp4则存在于F盘的movie文件夹下
        // 如果是jpg或者mp3则通过它们的相对路径得到绝对路径
//        if (filename.endsWith("jpg")) {
//            path = getHttpServletRequest().getServletContext().getRealPath("/images/" + filename);
//        } else if (filename.endsWith("mp3")) {
//            path = getHttpServletRequest().getServletContext().getRealPath("/musics/" + filename);
//        } else if (filename.endsWith("mp4")) {
//            path = "F:\\movie\\" + filename;
//        }


//        String time = new SimpleDateFormat("yyyyMMdd").format(new Date());
//        path =  GunsProperties.fileUploadPath + time + "/" + filename;

        path = TransferProperties.fileUploadPath + filename;
        FileInputStream fis = new FileInputStream(path);
        byte buff[] = new byte[2048];
        int len = 0;
        OutputStream os = response.getOutputStream();
        while ((len = fis.read(buff)) > 0) {
            os.write(buff, 0, len);
        }
        os.close();
        fis.close();

    }


}
